import { ExceptionFilter, Catch, ArgumentsHost, HttpStatus } from '@nestjs/common';
import { Response } from 'express';
import { ApiResponse, ResponseCode } from '../interfaces/response.interface';

@Catch()
export class AuthExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    
    // 处理JWT过期或无效token的情况
    if (exception.name === 'TokenExpiredError' || exception.name === 'JsonWebTokenError') {
      const responseBody: ApiResponse<null> = {
        code: ResponseCode.UNAUTHORIZED,
        message: '登录已过期，请重新登录',
        timestamp: Date.now(),
      };
      
      response.status(HttpStatus.UNAUTHORIZED).json(responseBody);
      return;
    }
    
    // 处理其他未授权访问
    if (exception.status === HttpStatus.UNAUTHORIZED) {
      const responseBody: ApiResponse<null> = {
        code: ResponseCode.UNAUTHORIZED,
        message: '未授权访问，请先登录',
        timestamp: Date.now(),
      };
      
      response.status(HttpStatus.UNAUTHORIZED).json(responseBody);
      return;
    }
    
    // 其他异常继续抛出
    throw exception;
  }
}